package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
   private MinioClient minioClient;
  @Autowired
  private MinioProperties minioProperties;
    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 1.创建minioClient
        // 2.判断是否有桶
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        if (!bucketExists) {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .build());
        }
        // 3.设置权限
        String policy = """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """;
            policy = policy.formatted(minioProperties.getBucketName());
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(policy).build());
        // 4.上传 名称重复问题，避免覆盖
//        minioClient.uploadObject() 设置本地磁盘
//        minioClient.putObject()  本地不存在，在运行内存中
      // 方案一  String fileName = UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename();
        // 桶中穿件文件夹/文件名
        String newDay = new SimpleDateFormat("yyyyMMdd").format(new Date())+ file.getOriginalFilename();;
        String ObjectName =newDay + "/" + UUID.randomUUID().toString().replace("-", "")+"_" + file.getOriginalFilename();
         minioClient.putObject(PutObjectArgs.builder()
                         .bucket(minioProperties.getBucketName()) // 桶名字
                 /**
                  * 参数1：文件输入流（数据）
                  * 参数2：上传文件的大小
                  * 参数3：是否进行切割上传 -1 切割大小 默认16M
                  */
                         .stream(file.getInputStream(),file.getSize(),-1)
                         .object(ObjectName)
                         .contentType(file.getContentType())
                 .build());
        // 5.拼接url 端点 + / + 桶名 + / + objectName
        String url = String.join("/", minioProperties.getEndpoint(),minioProperties.getBucketName(), ObjectName);
        return url;
    }
}
